package com.ficv.tucanalmovil.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.RememberMeServices;
import org.springframework.security.web.context.SecurityContextRepository;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ficv.tucanalmovil.dominio.People;

@Controller
@RequestMapping("/ajaxLogin")
public class AjaxLoginController {
	
	
	private static final Logger logger = LoggerFactory.getLogger(AjaxLoginController.class);

		
	
@Autowired
@Qualifier("authenticationManager")
AuthenticationManager authenticationManager;

@Autowired
SecurityContextRepository repository;

@Autowired
RememberMeServices rememberMeServices;

@RequestMapping(value="get")
@ResponseBody
public String login(@RequestParam(required=false, defaultValue="user") String username, 
		@RequestParam(required=false, defaultValue="user") String password) {
	
	logger.info("fetching login get " + username);
	return "OK";
}

@RequestMapping(value="post")
public @ResponseBody ResponseEntity<LoginStatus>  performLogin(
@RequestParam String username, 
@RequestParam String password,
HttpServletRequest request, HttpServletResponse response) 
{
	LoginStatus result= new LoginStatus(false, null);
	logger.info("fetching login post " + username);
	try {	
UsernamePasswordAuthenticationToken token = 
new UsernamePasswordAuthenticationToken(username, password);

Authentication auth = authenticationManager.authenticate(token);
SecurityContextHolder.getContext().setAuthentication(auth);
repository.saveContext(SecurityContextHolder.getContext(), request, response);
rememberMeServices.loginSuccess(request, response, auth);

result= new LoginStatus(auth.isAuthenticated(), auth.getName());

} catch (Throwable ex) {
	result = new LoginStatus(false, username, ex.getMessage());

}
	logger.info("end login post " + result);
return new ResponseEntity<LoginStatus>(result, getResponseHeaders(), HttpStatus.OK);
}




@RequestMapping(value="getNFm")
public @ResponseBody ResponseEntity<LoginStatus>  getNfm(@RequestParam String username, @RequestParam String countryNumber, HttpServletRequest request, HttpServletResponse response) {
	LoginStatus result= new LoginStatus(false, null);
	logger.info("fetching Nfm post " + username);
	try {	
		//TODO: hay que buscar el username, si ya existe es una nueva instalacion de numero existente (o ataque) y tiene que verificar el numero, si no existe generamos un nFm para el deviceID(username) y lo devolvemos con la password, hay q guardar nFm y deviceId (vendrá id o imei)
		
		People  people=People.findPeoplesByDeviceIdEquals(username).getSingleResult();
		if(people==null) {
			DeviceController dv = new DeviceController();
			dv.getConfig(request, username, "Newbie!!!", "Newbie???", "N", "0", "newbieActivity", "FFFFFF", "0.1.11", "60000","20","");		
			  people=People.findPeoplesByDeviceIdEquals(username).getSingleResult();
		}
		
		username=countryNumber + people.getId();
		people.setDeviceId(username);
		people.merge();
		
		String pwd=UserServiceImpl.getPwd(username);
		UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username,pwd);
		
		Authentication auth = authenticationManager.authenticate(token);
		SecurityContextHolder.getContext().setAuthentication(auth);
		repository.saveContext(SecurityContextHolder.getContext(), request, response);
		rememberMeServices.loginSuccess(request, response, auth);
		
		result= new LoginStatus(auth.isAuthenticated(), auth.getName(),pwd);

	} catch (Throwable ex) {
		result = new LoginStatus(false, username, ex.getMessage());
	
	}
	
	logger.info("end getNFm post " + username + ": " + result);
	return new ResponseEntity<LoginStatus>(result, getResponseHeaders(), HttpStatus.OK);
}




private HttpHeaders getResponseHeaders() {
	HttpHeaders responseHeaders = new HttpHeaders();
	responseHeaders.set("Access-Control-Allow-Origin", "*");
	responseHeaders.set("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
	responseHeaders.set("Access-Control-Allow-Headers", "Origin, x-requested-with, Set-Cookie, accept");
	responseHeaders.set("Access-Control-Max-Age", "86400");

	return responseHeaders;
}

public class LoginStatus {
	 
    private final boolean loggedIn;
    private final String username;
    private final String pwd;    
 
    public LoginStatus(boolean loggedIn, String username,String pwd) {
      this.loggedIn = loggedIn;
      this.username = username;
      this.pwd=pwd;
    }
 
    public LoginStatus(boolean loggedIn, String username) {
        this.loggedIn = loggedIn;
        this.username = username;
        this.pwd=null;
      }
    
    public boolean isLoggedIn() {
      return loggedIn;
    }
 
    public String getUsername() {
      return username;
    }
    
    public String getPwd() {
        return pwd;
    }    
    
  }


}
